package com.example.aicooking.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.aicooking.entity.dto.ChatHistoryResponse;
import com.example.aicooking.entity.dto.DifyMessageResponse;
import com.example.aicooking.service.DifyService;
import com.example.aicooking.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;


import java.util.ArrayList;
import java.util.Map;

@RestController
@RequestMapping("/api/chat")
@Slf4j
public class ChatController {

    @Autowired
    private DifyService difyService;

    @PostMapping("/send")
    public ResponseEntity<String> sendMessage(@RequestBody Map<String, String> request) {
        try {
            String message = request.get("message");
            String userId = request.get("userId");

            if (StringUtils.isEmpty(message)) {
                return ResponseEntity.badRequest().body("消息不能为空");
            }

            if (StringUtils.isEmpty(userId)) {
                return ResponseEntity.badRequest().body("用户ID不能为空");
            }

            // 直接使用userId，不需要包装成对象
            log.info("用户 {} 发送消息: {}", userId, message);

            return difyService.sendMessage(message, userId,"app2");
        } catch (Exception e) {
            log.error("发送消息失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("发送消息失败: " + e.getMessage());
        }
    }


    //    @GetMapping("/conversations")
//    public ResponseEntity<String> getConversations(
//            @RequestParam String userId,
//            @RequestParam(required = false) String lastId,
//            @RequestParam(required = false) Integer limit,
//            @RequestParam(required = false) Boolean pinned) {
//        try {
//            if (StringUtils.isEmpty(userId)) {
//                return ResponseEntity.badRequest().body("{\"error\": \"用户ID不能为空\"}");
//            }
//
//            log.info("获取用户 {} 的会话列表", userId);
//            return difyService.getConversations(userId, lastId, limit);
//        } catch (Exception e) {
//            log.error("获取会话列表失败", e);
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
//                    .body("{\"error\": \"获取会话列表失败\", \"message\": \"" + e.getMessage() + "\"}");
//        }
//    }
    @GetMapping("/history")
    public ResponseEntity<ChatHistoryResponse> getMessageHistory(
            @RequestParam String userId,
            @RequestParam String conversationId,
            @RequestParam(required = false) String firstId,
            @RequestParam(required = false) Integer limit) {
        try {
            if (StringUtils.isEmpty(userId)) {
                return ResponseEntity.badRequest().body(null);
            }

            if (StringUtils.isEmpty(conversationId)) {
                return ResponseEntity.badRequest().body(null);
            }

            // 使用与发送消息时相同的用户ID格式
            String difyUserId = userId;  // 直接使用传入的userId，不做修改

            log.info("获取用户 {} 的历史消息, conversationId: {}, firstId: {}, limit: {}",
                    difyUserId, conversationId, firstId, limit);

            return difyService.getMessageHistory(difyUserId, conversationId, firstId, limit, "app2");
        } catch (Exception e) {
            log.error("获取历史消息失败: {}", e);
            ChatHistoryResponse errorResponse = new ChatHistoryResponse();
            errorResponse.setLimit(limit != null ? limit : 20);
            errorResponse.setHasMore(false);
            errorResponse.setData(new ArrayList<>());
            return ResponseEntity.ok(errorResponse);
        }
    }
}
